package logic

import (
	"context"
	"strings"

	"mall/common/errorx"
	"mall/service/backend/model"
	"mall/service/backend/rpc/internal/svc"
	"mall/service/backend/rpc/types/backend"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateMemberLevelLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateMemberLevelLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateMemberLevelLogic {
	return &CreateMemberLevelLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateMemberLevelLogic) CreateMemberLevel(in *backend.CreateMemberLevelReq) (*backend.CreateMemberLevelResp, error) {
	name := strings.TrimSpace(in.Name)
	if len(name) == 0 {
		return nil, errorx.Status(errorx.ERROR_MEMBER_LEVEL_NAME_REQUIRED, "")
	}

	filterMap := make(map[string]map[string][]interface{})
	filterMap[model.MemberLevelColumns.Name] = map[string][]interface{}{
		"equalTo": []interface{}{name},
	}
	var pageSize int64 = 1
	_, count, err := l.svcCtx.MemberLevel.GetList(l.ctx, model.M{
		"pageSize": pageSize,
		"select":   ",",
	}, 0, filterMap)
	if err != nil {
		return nil, err
	}

	if count > 0 {
		return nil, errorx.Status(errorx.ERROR_MEMBER_LEVEL_NAME_EXISTS, "")
	}

	var ml model.MemberLevel
	ml.Name = in.Name
	ml.Slug = in.Slug
	ml.Description = in.Desc
	ml.ThumbnailID = uint64(in.MediaId)
	ml.ThumbnailURL = in.MediaUrl
	ml.GrowthThreshold = uint(in.Integral)
	ml.PrivilegeMemberPrice = uint8(in.WithMemberPrice)
	ml.PrivilegePromotion = uint8(in.WithPromotion)
	ml.PrivilegeFreeFreight = uint8(in.WithFreeFreight)
	ml.PrivilegeComment = uint8(in.WithComment)
	ml.PrivilegeSignIn = uint8(in.WithSignIn)
	ml.PrivilegeBirthday = uint8(in.WithBirthday)
	ml.FreeFreightThreshold = uint64(in.FreeFreight)
	ml.GrowthPerComment = uint(in.IntegralForComment)
	ml.TaskCount = uint(in.TaskCount)
	ml.IsDefault = uint8(in.IsDefault)
	err = l.svcCtx.MemberLevel.Insert(l.ctx, &ml)
	if err != nil {
		return nil, err
	}

	return &backend.CreateMemberLevelResp{}, nil
}
